package com.missilike.biz.impl;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.missilike.biz.IMilAccountService;
import com.missilike.biz.IMilOrderService;
import com.missilike.biz.IMilTradeRecordService;
import com.missilike.core.domain.GoodsProperties;
import com.missilike.core.domain.alipay.AlipayCashWithdrawalOrder;
import com.missilike.core.domain.alipay.AlipayCashWithdrawalResult;
import com.missilike.core.domain.alipay.AlipayNotifyResult;
import com.missilike.core.domain.alipay.AlipayOrder;
import com.missilike.core.enums.OrderStatusType;
import com.missilike.core.enums.OrderType;
import com.missilike.core.exception.BizException;
import com.missilike.core.result.BizResultCode;
import com.missilike.core.service.IAlipayService;
import com.missilike.core.utils.OrderUtils;
import com.missilike.domain.mapper.MilOrderInfoMapper;
import com.missilike.domain.request.OrderForm;
import com.missilike.domain.response.MilAccountInfo;
import com.missilike.domain.response.MilOrderInfo;
import com.missilike.repository.entity.MilOrder;
import com.missilike.repository.entity.MilTradeRecord;
import com.missilike.repository.mapper.MilOrderMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pengpengli
 * @since 2018-12-19
 */
@Service
public class MilOrderServiceImpl extends ServiceImpl<MilOrderMapper, MilOrder> implements IMilOrderService {
    @Autowired
    private GoodsProperties goodsProperties;

    @Autowired
    private IAlipayService alipayService;

    @Autowired
    private IMilAccountService milAccountService;

    @Autowired
    private IMilTradeRecordService milTradeRecordService;

    /**
     * 发起支付
     * @param orderForm
     * @return
     */
    @Override
    public String prePay(OrderForm orderForm) {
        String payResult = "";
        milAccountService.getAccount(orderForm.getAccountId());
        String orderId = OrderUtils.getUniqueOrder();
        LocalDateTime time = LocalDateTime.now();
        LocalDateTime timeOut = time.plusMinutes(goodsProperties.getTimeoutMinute());
        String timeoutExpress = goodsProperties.getTimeoutMinute() + "m";
        String amount = orderForm.getOrderAmount().setScale(2).toString();
        String orderBody = "购买糜子币" + amount + "元";
        if (orderForm.getOrderType() == OrderType.ALIPAY.getValue()) {
            AlipayOrder order = new AlipayOrder();
            order.setOutTradeNo(orderId);
            order.setBody("您购买糜子币" + amount + "元");
            order.setPassbackParams(goodsProperties.getParams());
            order.setSubject(goodsProperties.getSubject());
            order.setTimeoutExpress(timeoutExpress);
            order.setProductCode(goodsProperties.getProductCode());
            order.setTotalAmount(amount);
            payResult = alipayService.alipay(order);
            if (StringUtils.isBlank(payResult)) {
                return payResult;
            } else {
                insertOrder(orderForm, orderId, time, timeOut, amount, OrderStatusType.START.getValue(), orderBody);
            }
        }
        return payResult;
    }

    /**
     * 支付宝支付回调
     * @param request
     * @return
     */
    @Override
    public Boolean alipayNotify(HttpServletRequest request) {
        AlipayNotifyResult result = alipayService.signVerified(request);
        if (!result.getSignVerified()) {
            return false;
        }
        MilOrder order = baseMapper.selectOne(new QueryWrapper<MilOrder>().lambda()
                .eq(MilOrder::getOrderId, result.getOutTradeNo()));
        order.setOrderStatus(1);
        order.setTradeNo(result.getTradeNo());
        baseMapper.updateById(order);

        //增加余额
        milAccountService.changeBalance(order.getAccountId(),order.getOrderAmount());

        MilTradeRecord milTradeRecord = new MilTradeRecord();
        milTradeRecord.setAccountId(order.getAccountId());
        milTradeRecord.setCreateTime(order.getCreateTime());
        milTradeRecord.setOrderId(order.getOrderId());
        milTradeRecord.setTradeAmount(order.getOrderAmount());
        milTradeRecord.setTradeType(1);
        //添加充值记录
        milTradeRecordService.save(milTradeRecord);

        return true;
    }

    /**
     * 支付宝提现
     * @param orderForm
     * @return
     */
    @Override
    public Boolean cashWithdrawal(OrderForm orderForm) throws AlipayApiException {
        String orderId = OrderUtils.getUniqueCashWithdrawalOrder();
        LocalDateTime time = LocalDateTime.now();
        String amount = orderForm.getOrderAmount().setScale(2).toString();
        String orderBody = "提现取出" + amount + "元";
        MilAccountInfo milAccountInfo = milAccountService.getAccount(orderForm.getAccountId());
        if (StringUtils.isBlank(milAccountInfo.getAlipayAccount()) || StringUtils.isBlank(milAccountInfo.getAlipayName())) {
            throw new BizException(BizResultCode.NO_ALIPAY_ACCOUNT);
        }
        if (orderForm.getOrderType() == OrderType.ALICASH.getValue()) {
            AlipayCashWithdrawalOrder order = new AlipayCashWithdrawalOrder();
            order.setAmount(amount);
            order.setBizNo(orderId);
            order.setUserName(milAccountInfo.getAlipayName());
            order.setAccount(milAccountInfo.getAlipayAccount());
            AlipayCashWithdrawalResult result = alipayService.alipayCashWithdrawal(order);
            if (!result.getResult()) {
                return false;
            }
            insertOrder(orderForm, orderId, time, time, amount, OrderStatusType.FINISH.getValue(), orderBody);
        }
        return true;
    }

    @Override
    public IPage<MilOrderInfo> getOrderList(IPage<MilOrder> page,String account) {
        IPage<MilOrder> milAccountIPage = baseMapper.selectPage(page, new QueryWrapper<MilOrder>()
                .lambda()
                .likeRight(MilOrder::getAccountId,account)
        );
        return MilOrderInfoMapper.MAPPER.pageConvert(milAccountIPage);
    }

    /**
     * 添加订单记录
     * @param orderForm
     * @param orderId
     * @param time
     * @param timeOut
     * @param amount
     */
    private void insertOrder(OrderForm orderForm, String orderId, LocalDateTime time, LocalDateTime timeOut, String amount, Integer orderStatus, String orderBody) {
        MilOrder milOrder = new MilOrder();
        milOrder.setOrderId(orderId);
        milOrder.setOrderAmount(orderForm.getOrderAmount());
        milOrder.setOrderBody(orderBody);
        milOrder.setOrderType(orderForm.getOrderType());
        milOrder.setProductCode(goodsProperties.getProductCode());
        milOrder.setUpdateTime(time);
        milOrder.setTimeOut(timeOut);
        milOrder.setAccountId(orderForm.getAccountId());
        milOrder.setCreateTime(time);
        milOrder.setOrderStatus(orderStatus);
        milOrder.setTradeNo("");
        baseMapper.insert(milOrder);
    }
}
